import { defineStore } from "pinia";
import { ref } from "vue";
// http://m701.music.126.net
// http://m702.music.126.net
// http://m801.music.126.net
// http://m802.music.126.net
// http://m8.music.126.net
// http://m7.music.126.net
import { getMusicUrl } from "@/apis/song";

export const useAudioStore = defineStore("audio", () => {
  const audioContext = uni.createInnerAudioContext({
    useWebAudioImplement: false,
  });

  const activeMusicList = ref([]);
  const privileges = ref([]);
  const playIndex = ref(0);
  const musicLevel = ref("higher");
  const duration = ref(0);
  const currentTime = ref(0);

  const getMusicUrlData = async (id) => {
    const data = await getMusicUrl({
      id,
      level: musicLevel.value,
    });
    const songResult = data.data[0];
    if (data.code !== 200)
      return uni.showToast({ title: "播放出错", icon: "none" });
    if (songResult.freeTrialPrivilege.cannotListenReason !== null)
      uni.showToast({ title: "试听 30 秒", icon: "none" });
    audioContext.src = songResult.url;
    audioContext.autoplay = true;
    playStatus.value = true;
  };

  const playStatus = ref(false);

  // 播放
  const play = () => {
    audioContext.play();
    playStatus.value = true;
  };

  // 暂停
  const pause = () => {
    audioContext.pause();
    playStatus.value = false;
  };

  // 监测播放进度
  audioContext.onCanplay(() => {
    // duration.value = audioContext.duration
  });

  // 监测播放进度
  audioContext.onTimeUpdate(() => {
    duration.value = audioContext.duration;
    currentTime.value = audioContext.currentTime;
  });

  return {
    activeMusicList,
    privileges,
    playIndex,
    duration,
    currentTime,
    playStatus,
    getMusicUrlData,
    play,
    pause,
  };
});
